package com.bdqn.t350.ch04mybatisplus.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.t350.ch04mybatisplus.pojo.User;
import com.bdqn.t350.ch04mybatisplus.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Resource
    UserService userService;

    @RequestMapping("/index")
    public String index() {
        System.out.println("index...");
        return "index";
    }

    @ResponseBody
    @RequestMapping("/list")
    public Object list() {
        return userService.getList();
    }

    // @ResponseBody
    @RequestMapping("/page")
    public Object page(Integer current, Integer size, Model model) {
        IPage page = new Page(current, size);
        //return userService.getPageList(page);
        page = userService.getPageList(page);
        model.addAttribute("page", page);
        return "index";
    }


    @RequestMapping("/login")
    public Object login(String username, String pwd, Model model, HttpServletRequest request, HttpSession session) {
        User user = null;
        try {
            user = userService.getUser(username, pwd);
            if (user != null) {
                session.setAttribute("user", user);
                return "redirect:/welcome/index";
            }
            return "redirect:error1";
        } catch (Exception e) {
            return "redirect:error1";
        }
    }

    @RequestMapping("/error1")
    public Object error1() {
        System.out.println("error1");
        return "error";
    }

    @RequestMapping("/error2")
    public Object error2() {
        System.out.println("error2");
        return "error2";
    }

}
